<?php
/**
 * 父类
 * User: narnia
 * Date: 2017/5/19
 * Time: 11:28
 */
namespace LancerWechat;
class WechatService
{
    /**
     * @var array   配置
     *          'global 全局配置
     *                  appID   应用id
     *                  appsecret   应用秘钥
     *                  aeskey      消息秘钥
     *
     *          'oauth' 授权配置
     *                  scope   授权模式
     *                  redirectUri 回调页面
     *
     *          'log'   日志配置
     *                  path    路径
     */
    public $config;
    /**
     * @var WechatOauth 授权类
     */
    public $oauth;
    /**
     * @var WechatMenu 菜单类
     */
    public $menu;
    /**
     * @var WechatUser 用户类
     */
    public $user;
    /**
     * @var WechatAccessToken 用户类
     */
    public $accessToken;
    /**
     * @var WeChatVerify 验证类
     */
    public $verify;
    /**
     * @var WechatPay 支付类
     */
    public $pay;
    /**
     * @var WechatTemplate 模板消息类
     */
    public $template;
    /**
     * @var array   微信接口url
     */
    public $urls = [
        //  授权url
        'oauth' => [
            // 获取code
            'code' => 'https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={redirectUri}&response_type=code&scope={scope}&state={state}#wechat_redirect',
            // 获取token
            'access_token' => 'https://api.weixin.qq.com/sns/oauth2/access_token?appid={appid}&secret={secret}&code={code}&grant_type=authorization_code',
            // 获取用户
            'user' => 'https://api.weixin.qq.com/sns/userinfo?access_token={access_token}&openid={openid}&lang=zh_CN'
        ],
        // 菜单url
        'menu' => [
            // 创建菜单
            'create' => 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token={access_token}'
        ],
        // 用户url
        'user' => [
            // 获取用户
            'get' => 'https://api.weixin.qq.com/cgi-bin/user/info?access_token={access_token}&openid={openid}&lang=zh_CN'
        ],
        // 订单url
        'order' => [
            // 统一下单
            'unifiedorder' => "https://api.mch.weixin.qq.com/pay/unifiedorder"
        ],
        // 模板消息url
        'template' => [
            'send' => 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}',
            'getList' => 'https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token={access_token}',
        ],
        // 媒体
        'media' => [
            'uploadImg' => 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token={access_token}'
        ],
        'kf' => [
            'send' => 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={access_token}'
        ]
    ];
    /**
     * @var array 实例化的类
     */
    protected $class = [
        'oauth' => \LancerWechat\WechatOauth::class,
        'menu' => \LancerWechat\WechatMenu::class,
        'user' => \LancerWechat\WechatUser::class,
        'accessToken' => \LancerWechat\WechatAccessToken::class,
        'verify' => \LancerWechat\WeChatVerify::class,
        'pay' => \LancerWechat\Pay\WechatPay::class,
        'template' => \LancerWechat\WechatTemplate::class,
        'media' => \LancerWechat\WechatMedia::class,
        'kf' => \LancerWechat\WechatKF::class,
    ];

    /**
     * WechatService constructor. 初始化
     */
    public function init()
    {
        //=======【curl代理设置】===================================
        /**
         * TODO：这里设置代理机器，只有需要代理的时候才设置，不需要代理，请设置为0.0.0.0和0
         * 本例程通过curl使用HTTP POST方法，此处可修改代理服务器，
         * 默认CURL_PROXY_HOST=0.0.0.0和CURL_PROXY_PORT=0，此时不开启代理（如有需要才设置）
         * @var unknown_type
         */
        $this->config['global']['curl_proxy_host'] = "0.0.0.0";
        $this->config['global']['curl_proxy_port'] = 0;
        //=======【上报信息配置】===================================
        /**
         * TODO：接口调用上报等级，默认紧错误上报（注意：上报超时间为【1s】，上报无论成败【永不抛出异常】，
         * 不会影响接口调用流程），开启上报之后，方便微信监控请求调用的质量，建议至少
         * 开启错误上报。
         * 上报等级，0.关闭上报; 1.仅错误出错上报; 2.全量上报
         * @var int
         */
        $this->config['pay']['report_level'] = 1;
        //=======【微信支付证书路径设置】=====================================
        /**
         * TODO：设置商户证书路径
         * 证书路径,注意应该填写绝对路径（仅退款、撤销订单时需要，可登录商户平台下载，
         * API证书下载地址：https://pay.weixin.qq.com/index.php/account/api_cert，下载之前需要安装商户操作证书）
         * @var path
         */
        $this->config['pay']['sslcert_path'] = '../cert/apiclient_cert.pem';
        $this->config['pay']['sslkey_path'] = '../cert/apiclient_key.pem';

        foreach ($this->class as $k => $c) {
            $this->$k = new $c();
            $this->$k->refreshConfig($this->config);
        }
        $this->pay->load();
    }

    /**
     * @param array $config 创建配置
     */
    public function createConfig(array $config = [])
    {
        $config = array_merge($config, [
            'log' => ['path' => 'data/logs/wechat/']
        ]);
        $this->config = $config;
    }

    /**
     * 自定义配置
     * @param array $config 关联数组
     */
    public function setConfig(array $config = [])
    {
        foreach ($config as $k => $v) {
            $this->config[$k][key($v)] = $config[$k][key($v)];
        }
        foreach ($this->class as $k => $c) {
            $this->$k->refreshConfig($this->config);
        }
    }

    /**
     * @param array $config 刷新配置
     */
    public function refreshConfig(array $config)
    {
        $this->config = $config;
    }

    /**
     * 批量替换接口url值, 获取url
     * @param array $urlRplaceArr 替换的关联数组
     * @param array $key 键 如 ['oauth','code']
     */
    public function getUrl(array $urlRplaceArr, array $key)
    {
        $url = $this->urls[$key['0']][$key['1']];
        foreach ($urlRplaceArr as $key => $value) {
            $url = str_replace($key, $value, $url);
        }
        return $url;
    }
}
